package com.digitalchina.lxnsy.activity.farmVideo;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import androidx.legacy.app.ActivityCompat;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.base.BaseHtmlActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.videoupload.FileUtils;
import com.digitalchina.lxnsy.videoupload.MediaUtils;
import com.digitalchina.lxnsy.videoupload.TXUGCPublish;
import com.digitalchina.lxnsy.videoupload.TXUGCPublishTypeDef;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;

public class AgrVideoEditActivity extends BaseHtmlActivity implements TXUGCPublishTypeDef.ITXVideoPublishListener {

    public static final int REQUESTCODE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_CODE_RECORD_VIDEO = 3;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private String mVideoPath;
    private TXUGCPublish mVideoPublish = null;
    // signature计算规则可参考 https://www.qcloud.com/document/product/266/9221
    private String mSignature = "";


    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
//    private ArrayList<ImageItem> selectedImageList = new ArrayList<>(); //当前选择的所有图片
//    private String filePath = ""; // 图片地址

    ProgressBar pb;
    TextView tv;
    Dialog mDialog;

    //视频类型 SMALL_VIDEO 小视频
    String videoType = "";

    int MAX_SMALL_VIDEO_TIME = 60;
    int MAX_BIG_VIDEO_TIME = 1800;

    @Override
    protected void loadHtml() {
        webView.addJavascriptObject(new JsApi(), null);
        loadUrl("video-video-edit");
        setTitle("视频编辑");


        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);

        mDialog = new Dialog(activity, R.style.NoBackGroundDialog);


        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_progress_bar, null);
        pb = view.findViewById(R.id.progress_bar);
        tv = view.findViewById(R.id.textView);
        mDialog.setCancelable(false);
        mDialog.setContentView(view);


//        new Thread() {
//            @Override
//            public void run() {
//                for (int i = 1; i < 101; i++) {
//                    Message loMsg = new Message();
//                    if (i < 100) {
//                        loMsg.what = MSG.MSG_SEND_VERIFY_CODE_TIP;
//                        loMsg.obj = i;
//                    } else {
//                        loMsg.what = MSG.MSG_SEND_VERIFY_CODE_END;
//                    }
//                    mHandler.sendMessage(loMsg);
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                    }
//                }
//            }
//        }.start();

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void setHandler() {
        super.setHandler();
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                dismissDialog();
                switch (message.what) {
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        FileVO fileVO = FastJsonUtil.getBean(message.obj.toString(), "body", "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            callJsMethod("setImg", new String[]{fileVO.getName()});
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_0:
                        beginUpload();
                        break;
//                    case MSG.MSG_SEND_VERIFY_CODE_TIP:
//                        pb.setProgress(Integer.parseInt(message.obj.toString()));
//                        tv.setText(message.obj.toString()+"%");
//                        break;
                }
                return false;
            }
        });
    }

    public class JsApi {

        @JavascriptInterface
        public void save(Object msg) {
            setResult(RESULT_OK);
        }

        //设置签名
        @JavascriptInterface
        public void setSignature(Object msg) {
            mSignature = msg.toString();
        }

        //选择视频
        @JavascriptInterface
        public void selectVideo(Object msg) {
            videoType = msg.toString();
            if (verifyStoragePermissions()) ;
            chooseFile();
        }

        //录制视频
        @JavascriptInterface
        public void selectCamera(Object msg) {

            videoType = msg.toString();
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  // 表示跳转至相机的录视频界面
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.4);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, "");    // 表示录制完后保存的录制，如果不写，则会保存到默认的路径，在onActivityResult()的回调，通过intent.getData中返回保存的路径
            if ("SMALL_VIDEO".equals(videoType)) {
                //小视频最多1分钟
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, MAX_SMALL_VIDEO_TIME);   // 设置视频录制的最长时间
            } else {
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, MAX_BIG_VIDEO_TIME);   // 设置视频录制的最长时间
            }

            startActivityForResult(intent, REQUEST_CODE_RECORD_VIDEO);  // 跳转
        }

        //选择图片
        @JavascriptInterface
        public void selectImg(Object msg) {
            Intent intent = new Intent(activity, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        }

        //开始上传视频
        @JavascriptInterface
        public void upload(Object msg) {
            Message message = new Message();
            message.what = MSG_S_0;
//            message.obj = msg;
            mHandler.sendMessage(message);
        }
    }


    public boolean verifyStoragePermissions() {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    private void beginUpload() {
        mDialog.show();
        tv.setText("0%");
        pb.setProgress(0);
        if (mVideoPublish == null) {
            mVideoPublish = new TXUGCPublish(this.getApplicationContext(), "independence_android");
            // mVideoPublish.setAppId(123456);
            mVideoPublish.setListener(this);
        }

        TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
        param.signature = mSignature;
        param.videoPath = mVideoPath;
        int publishCode = mVideoPublish.publishVideo(param);
        if (publishCode != 0) {
            showToast("发布失败，错误码：" + publishCode);
        }

    }

    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        Intent wrapIntent = Intent.createChooser(intent, null);
        startActivityForResult(wrapIntent, REQUESTCODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE) {
            //选择视频
            if (resultCode == RESULT_OK) {

                if ("SMALL_VIDEO".equals(videoType)) {
                    if (MAX_SMALL_VIDEO_TIME < getVideoDuration(data.getData())) {
                        showToast("请选择1分钟内的小视频！");
                        return;
                    }
                } else {
                    if (MAX_SMALL_VIDEO_TIME > getVideoDuration(data.getData())) {
                        showToast("请选择大于1分钟的农技视频！");
                        return;
                    }
                }
                mVideoPath = FileUtils.getRealPathFromUri(this, data.getData());
                setVideoPath();
            }

        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                showDialog("上传中，请稍候");
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                filePath = images.get(0).path;
//                selectedImageList.addAll(images);
                BusinessFile.imageCompressAndUpload(activity, images.get(0).path, mHandler);
            }
        } else if (requestCode == REQUEST_CODE_RECORD_VIDEO) {
            //拍摄视频
            if (resultCode == RESULT_OK) {

                if ("SMALL_VIDEO".equals(videoType)) {
                    if (MAX_SMALL_VIDEO_TIME < getVideoDuration(data.getData())) {
                        showToast("请选择1分钟内的小视频！");
                        return;
                    }
                } else {
                    if (MAX_SMALL_VIDEO_TIME > getVideoDuration(data.getData())) {
                        showToast("请选择大于1分钟的农技视频！");
                        return;
                    }
                }

                mVideoPath = FileUtils.getRealPathFromUri(this, data.getData());
                setVideoPath();
            }

        }
    }


    private void setVideoPath() {


        MediaUtils.getImageForVideo(mVideoPath, new MediaUtils.OnLoadVideoImageListener() {
            @Override
            public void onLoadImage(File file) {
                String s1 = Uri.fromFile(file).toString();
                String s2 = getFileNameWithSuffix(mVideoPath);
                callJsMethod("setVideo", new String[]{s1, s2});
                showDialog("上封面传中，请稍候");
                BusinessFile.imageCompressAndUpload(activity, file.getPath(), mHandler);
            }
        });
    }

    /**
     * 保留文件名及后缀
     */
    public String getFileNameWithSuffix(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }
    }

    @Override
    public void onPublishProgress(long uploadBytes, long totalBytes) {
        pb.setProgress((int) (100 * uploadBytes / totalBytes));
        tv.setText((100 * uploadBytes / totalBytes) + "%");
    }

    @Override
    public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
        if (result.retCode == 0) {
            callJsMethod("setVideoID", new String[]{result.videoId});
        } else {
            showToast(result.descMsg);
        }
        mDialog.dismiss();
    }


    /**
     * get Local video duration
     *
     * @return
     */
    public int getVideoDuration(Uri mUri) {
        int duration= 0;
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();

        try {
            if (mUri != null) {
//                HashMap<String, String> headers=null;
//                if (headers == null) {
//                    headers = new HashMap<String, String>();
//                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
//                }
                mmr.setDataSource(this,mUri);
            }

            duration = Integer.parseInt(mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION))/1000;
        } catch (Exception ex) {
        } finally {
            mmr.release();
        }

        return duration;
    }


}
